package me.zhengjie.modules.security.service;

import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.service.CorporationService;
import me.zhengjie.security.corporationdetails.CorporationDetails;
import me.zhengjie.security.corporationdetails.CorporationDetailsService;
import me.zhengjie.security.corporationdetails.SimpleCorporationDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author yanhai
 */
@Service
public class CorporationDetailsServiceImpl implements CorporationDetailsService {

    public static final String DEFAULT_CORPORATION = "manager";

    @Autowired
    private CorporationService corporationService;

    @Override
    public CorporationDetails findByCorporationCode(String corporationCode) throws UsernameNotFoundException {
        // 默认写死管理员的集团编号(manager)
        SimpleCorporationDetails details = new SimpleCorporationDetails();
        if(DEFAULT_CORPORATION.equals(corporationCode)) {
            details.setCorporationCode(DEFAULT_CORPORATION);
            return details;
        }

        Corporation corporation = corporationService.getCorporationByCorporationCode(corporationCode);

        if (corporation == null) {
            throw new UsernameNotFoundException("corporationCode [" + corporationCode + "] not found");
        }

        details.setCorporationCode(corporation.getCorporationCode());
        return details;
    }
}
